package com.jw.controller;

import com.jw.entity.Person;
import com.jw.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/")
public class PersonController {

    private final PersonRepository personRepository;
    public PersonController() {
        personRepository=null;

    }
    @Autowired
    public PersonController(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @GetMapping("signup")
    public String showSignUpForm(Person person) {
        return "add-person";
    }

    @GetMapping("list")
    public String showUpdateForm(Model model) {
        model.addAttribute("jwpersons", personRepository.findAll());
        return "index";
    }

    @PostMapping("add")
    public String addNote(@Valid Person Person, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "add-person";
        }

        personRepository.save(Person);
        return "redirect:list";
    }

    @GetMapping("edit/{id}")
    public String showUpdateForm(@PathVariable("id") long id, Model model) {
        Person Person = personRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid Person Id:" + id));
        model.addAttribute("person", Person);
        return "update-person";
    }
    @PostMapping("update/{id}")
    public String updateNote(@PathVariable("id") long id, @Valid Person person, BindingResult result,
                             Model model) {
        if (result.hasErrors()) {
            person.setId(id);
            return "update-person";
        }

        personRepository.save(person);
        model.addAttribute("jwpersons", personRepository.findAll());
        return "index";
    }

    @GetMapping("delete/{id}")
    public String deleteNote(@PathVariable("id") long id, Model model) {
        Person person = personRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid Person Id:" + id));
        personRepository.delete(person);
        model.addAttribute("jwpersons", personRepository.findAll());
        return "index";
    }

    //不懂java？给你看个加法
    public static int jwadd(int a,int b){
        int i=9/0;
        int result=a+b;
        return result;

    }
}

